import useStore from "../../store/index";
import { confignArr } from "./ignore";
import type { Data } from "@/type/request";

const baseURL = import.meta.env.VITE_BASE_API;
const httpInterceptor = {
  // 拦截前触发
  invoke(options: UniApp.RequestOptions) {
    // 1. 非 http 开头需拼接地址
    if (!options.url.startsWith("http")) {
      options.url = baseURL + options.url;
    }
    // 2. 请求超时
    options.timeout = 10000;
    // 3. 添加小程序端请求头标识
    options.header = {
      "source-client": "miniapp",
      ...options.header,
    };
    const memberStore = useStore();
    if (memberStore.token) {
      const token = "Bear " + memberStore?.token;
      options.header.Authorization = token;
    }
  },
};
export const http = <T = any>(options: UniApp.RequestOptions) => {
  return new Promise<Data<T>>((resolve, reject) => {
    uni.request({
      ...options,
      success(res) {
        if (res.statusCode >= 200 && res.statusCode < 300) {
          if (confignArr.includes(options.url)) {
            resolve(res.data as any as Data<T>);
          } else if ((res.data as any).success) {
            resolve((res.data as any).data as Data<T>);
          } else {
            uni.showToast({
              icon: "none",
              title: (res.data as any).message || "请求错误",
            });
          }
        } else if (res.statusCode === 401) {
          // 401错误  -> 清理用户信息，跳转到登录页
          // const memberStore = useStore() 重置token
          uni.navigateTo({ url: "/pages/loginPage/loginPage" });
          uni.showToast({
            icon: "none",
            title: (res.data as Data<T>).message || "请求错误",
          });
          reject(res);
        } else {
          uni.showToast({
            icon: "none",
            title: (res.data as Data<T>).message || "请求错误",
          });
          reject(res);
        }
      },
      fail(err) {
        uni.showToast({
          icon: "none",
          title: "网络错误，换个网络试试",
        });
        reject(err);
      },
    });
  });
};

// 拦截 request 请求
uni.addInterceptor("request", httpInterceptor);
// 拦截 uploadFile 文件上传
uni.addInterceptor("uploadFile", httpInterceptor);
